var es = require('event-stream');
/**
 * @param {import('loopback').LoopBackApplication} app
 */
module.exports = function (app) {

  app.get("/test", async function (req, res) {

    await app.redlock.lock("wwwwwdd", 5000).then(async (lock) => {
      await later(3000, Math.random().toString())
      lock.unlock()
      let d = new Date()
      res.send({ stat: false, date: d.toLocaleTimeString() + "#" + d.getMilliseconds() })
    }, function () {
      let d = new Date()
      res.send({ date: d.toLocaleTimeString() + "#" + d.getMilliseconds(), stat: true })
    })
  })
  app.get("/steam", async function (req, res) {
    // app.models.food
    app.models.Food.createChangeStream((err, changes) => {
      changes.pipe(es.stringify()).pipe(process.stdout);
    })
  })
  app.get("/error", async function (req, res, next) {
    setTimeout(() => {
      throw new Error()
    }, 500)
  })
}

function later(time, msg) {
  msg && console.log("延时" + time + "," + msg);
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve(time);
    }, time);
  });
}